package com.outsourcing.bottle.ui;

import java.util.HashMap;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.BasicUIEvent;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.UICore;
/**
 * 
 * @author 06peng
 *
 */
public class LoginActivity extends BasicActivity implements BasicUIEvent, OnClickListener, Callback {
	
	private final int login = 1;
	private final int login_success = 2; 
	private final int login_error = 3;
	
	private EditText accountView;
	private EditText passwordView;
	private Button loginView;
	private ImageView close;
	private ImageView forget;
	
	private String username;
	private String password;
	private String deviceId;
	private TelephonyManager tm;
	private Handler handler;

	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		handler = new Handler(this);
		setContentView(R.layout.login);
		initWidget();
		tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
		deviceId = tm.getDeviceId();
		networkLocat();
	}

	private void initWidget() {
		accountView = (EditText) findViewById(R.id.login_account);
		passwordView = (EditText) findViewById(R.id.login_password);
		passwordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
					checkLogin();
				}
				return false;
			}
		});
		close = (ImageView) findViewById(R.id.close);
		close.setOnClickListener(this);
		forget = (ImageView) findViewById(R.id.login_forget);
		forget.setOnClickListener(this);
		loginView = (Button) findViewById(R.id.login);
		loginView.setOnClickListener(this);
	}
	
	
	@Override
	public void onClick(View v) {
		if (v == forget) {
			Intent intent = new Intent(this, ForgetPasswordActivity.class);
			startActivity(intent);
		} else if (v == close) {
			finish();
		} else if (v == loginView) {
			checkLogin();
		}
	}
	
	private void checkLogin() {
		username = accountView.getText().toString().trim();
		password = passwordView.getText().toString().trim();
		if (username.equals("")) {
			onToast(getString(R.string.login_txt_register_error_account));
			return;
		}
		if (password.equals("")) {
			onToast(getString(R.string.login_txt_reset_error));
			return;
		}
		UICore.eventTask(this, this, login, getString(R.string.init_data), null);
	}
	
	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case login:
			login();
			break;

		default:
			break;
		}
	}
	
	private void login() {
		String url = UrlConfig.login;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("username", username);
		paramsMap.put("password", password);
		paramsMap.put("device_token", deviceId);
		paramsMap.put("device_type", android.os.Build.MODEL);
		paramsMap.put("device_provider", android.os.Build.PRODUCT);
		paramsMap.put("device_version", android.os.Build.VERSION.RELEASE);
		paramsMap.put("lat", String.valueOf(AppContext.getInstance().getLatitude()));
		paramsMap.put("lng", String.valueOf(AppContext.getInstance().getLongitude()));
		if (countryIso != null && countryIso.equalsIgnoreCase("cn")) {
			paramsMap.put("location_mode", "1");
		} else {
			paramsMap.put("location_mode", "0");
		}
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
			if (result != null) {
				JSONObject obj = new JSONObject(result);
				JSONObject resultObj = obj.getJSONObject("results");
				int login_uid = resultObj.getInt("login_uid");
				if (login_uid != 0) {
					String login_token = resultObj.getString("login_token");
					AppContext.getInstance().setLogin_uid(login_uid);
					AppContext.getInstance().setLogin_token(login_token);
					SharedPreferences preferences = getSharedPreferences("Preferences_userinfo", Activity.MODE_APPEND);
					Editor editor = preferences.edit();
					editor.putInt("login_uid", login_uid);
					editor.putString("login_token", login_token);
					editor.commit();
					handler.sendEmptyMessage(login_success);
				} else {
					String errmsg = resultObj.getString("errmsg");
					Message message = Message.obtain(handler, login_error, errmsg);
					handler.sendMessage(message);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case login_success:
			Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
			startActivity(intent);
			LoginActivity.this.finish();
			break;
		case login_error:
			onToast((String) msg.obj);
			break;
		default:
			break;
		}
		return false;
	}
}
